/*****************************************************************************************
 **  Author:jxx 2022
 **  QQ:283591387
 **完整文档见：http://v2.volcore.xyz/document/api 【代码生成页面ViewGrid】
 **常用示例见：http://v2.volcore.xyz/document/vueDev
 **后台操作见：http://v2.volcore.xyz/document/netCoreDev
 *****************************************************************************************/
//此js文件是用来自定义扩展业务代码，可以扩展一些自定义页面或者重新配置生成的代码
import modelHeader from "../../produceinfo/goods_fittings/goodsFittings.vue"
import modelBody from "../goods_fittings_inventory/goodsFittingsInventory.vue"
import modelFooter from "../../inventoryinfo/goods_inventory_warehouse_xm/goodsInventoryWarehouse_xm.vue"
import gridHeader from "@/components/print/selectTemplet.vue"
import {
  mapMutations
} from "vuex";
import {
  ElMessage
} from 'element-plus'

let extension = {
  components: {
    //查询界面扩展组件
    gridHeader,
    gridBody: '',
    gridFooter: '',
    //新建、编辑弹出框扩展组件
    modelHeader: modelHeader,
    modelBody: modelBody,
    modelFooter: modelFooter
  },
  tableAction: '', //指定某张表的权限(这里填写表名,默认不用填写)
  buttons: {
    view: [],
    box: [],
    detail: []
  }, //扩展的按钮
  methods: {
    ...mapMutations(
      ("salesContractMX", ["storeRemoveForm", "storeChangeForm"])
    ),
    //下面这些方法可以保留也可以删除
    async onInit() {
      this.queryFields = ["Proposer", "CreateDate"]
      let startTime = await this.base.getOneWeekAgoDate()
      let endTime = await this.base.getDate(false) + " 23:59:59"
      this.searchFormFields.CreateDate = [startTime, endTime]
      this.detailOptions.textInline = false
      this.textInline = false
      this.editFormOptions.forEach(option => {
        option.forEach(item => {
          if (item.field == "Goods_name") {
            // item.remote = true
            item.extra = {
              icon: "el-icon-zoom-in",
              text: "选择产品",
              style: "color:#3a8ee6;font-size:13px;cursor:default",
              click: () => {
                this.$store.commit("setTabelText", true)
                this.$refs.modelHeader.open()
                // this.$refs.detail.rowData.forEach(item => {
                //   item.Goods_num = item.Goods_num_copy
                // })
              }
            }
          }
          if (item.field == "Goods_num") {
            item.extra = {
              icon: "el-icon-close",
              // text: "X",
              style: "color:#3a8ee6;font-size:13px;cursor:default;background-color: #f5f7fa;padding: 10px 15px;border-radius: 5px;box-shadow: 2px 2px 2px #d4d6d9;",
              click: () => {
                // console.log("this.editFormFields.Goods_num>0", this.editFormFields.Goods_num > 0)
                // console.log("item.Goods_num", item.Goods_num)
                // console.log("item", item)
                if (this.editFormFields.Goods_num > 0) {
                  this.$refs.detail.rowData.forEach(item => {
                    if (item.Goods_num) {
                      item.Goods_num = item.Goods_num * this.editFormFields.Goods_num
                    }
                  })
                } else {
                  this.$refs.detail.rowData.forEach(item => {
                    item.Goods_num = 0
                  })
                }

              }
            }
          }
        })
      })

      if (this.$route.path == "/q_produce_use" && JSON.stringify(this.$route.query) != '{}') {
        console.log("触发查询")
        await this.base.setSearchParamFn(this)
        // this.searchFormFields.Voucher_sub = null
        // this.searchFormFields.Goods_sub = null
        // this.searchFormFields.Goods_name = null
        // this.searchFormFields.Proposer = null
        // this.searchFormFields.Production_state = null
        // this.searchFormFields.AuditStatus = null
        // this.searchFormFields.Goods_num = [null, null]
        // this.searchFormFields.CreateDate = [null, null]
        // const selectList = ['Goods_num','Production_state','AuditStatus','CreateDate',]
        // this.searchFormOptions.forEach(item => {
        //   item.forEach(x => {
        //     if (selectList.includes(x.field)) {
        //       x.onChange = (v) => {
        //         this.$route.query = {}
        //       }
        //     }
        //   })
        // })
        setTimeout(() => {
          this.refresh()
        })
      }
    },
    async onInited() {
      if (this.$route.path != "/q_produce_use") {
        this.setFiexdSearchForm(true);
        this.height = 550 - 150;
        this.buttons.forEach(item => {
          if (item.value != "Search") {
            item.hidden = true
          }
        })
        this.detailOptions.buttons = []
      }
      if (this.$route.path == "/q_produce_return") {
        this.searchFormFields.AuditStatus = "1";
        this.searchFormFields.Production_state = "1";
      }
      // this.setFiexdSearchForm(true);
      // this.buttons.forEach(item => {
      //   if (item.name == "高级查询") {
      //     item.hidden = true
      //   }
      // })
      await this.detailOptions.buttons.splice(this.detailOptions.buttons.findIndex(item => item.name == "添加行"), 1)
      this.detailOptions.buttons.unshift({
        name: "配件表", //按钮名称
        icon: 'el-icon-plus', //按钮图标，参照iview图标
        type: 'primary',
        plain: true,
        onClick: function () { //触发事件

          if (!this.editFormFields.Goods_sub) {
            this.base.ElMessageFn("请先选择产品")
            return
          }
          if (!this.editFormFields.WHSE_jg) {
            this.base.ElMessageFn("请先选择机构")
            return
          }
          if (!this.editFormFields.WHSE_no) {
            this.base.ElMessageFn("请先选择有空闲工位的机构")
            return
          }
          if (this.rowschild) {
            this.rowschild.click()
          }
          let form = {
            产品编码: this.editFormFields.Goods_sub,
          }
          this.storeChangeForm(form);
          this.$store.commit("setTabelText", true)
          this.$refs.modelBody.open(this.editFormFields.Goods_sub,this.editFormFields.WHSE_no,this.editFormFields.WHSE_jg)
        }
      })
      this.detailOptions.buttons.unshift({
        name: "库存表", //按钮名称
        icon: 'el-icon-plus', //按钮图标，参照iview图标
        type: 'primary',
        plain: true,
        onClick: function () { //触发事件
          if (!this.editFormFields.Goods_sub) {
            this.base.ElMessageFn("请先选择产品")
            return
          }
          if (!this.editFormFields.WHSE_jg) {
            this.base.ElMessageFn("请先选择机构")
            return
          }
          if (!this.editFormFields.WHSE_no) {
            this.base.ElMessageFn("请先选择有空闲工位的机构")
            return
          }
          if (this.rowschild) {
            this.rowschild.click()
          }
          this.$store.commit("setTabelText", true)
          this.$refs.modelFooter.open(this.editFormFields.WHSE_no,this.editFormFields.WHSE_jg)
        }
      })

      // this.editFormOptions.forEach(x => {
      //   x.forEach(option => {
      //     if (option.field == "Goods_num") {
      //       option.onKeyPress = $event => {
      //         $event.target.addEventListener("keyup", (e) => {
      //           if (this.$refs.detail.rowData.length) {
      //             this.$refs.detail.rowData.forEach(item => {
      //               item.Goods_num = item.Goods_num_copy * e.target.value
      //             })
      //           }

      //         })
      //       }
      //     }
      //   })
      // })

      this.detailOptions.beginEdit = (row, column, index) => {
        if (this.$route.path != "/q_produce_use" || this.rowAuditStatus != 0) { //|| !this.CreateUserBoole
          return false
        }
        /*
             this.detailOptions.columns.forEach(item => {
               if (item.field == "WHSE_name") {
     
                 let selectUrl = `api/q_warehouse_locationList/getgoodslocation?bm=${row.Goods_sub}`
                 item.bind.data.forEach(d => {
                   d.hidden = true
                 })
                 this.http.post(selectUrl, {}, "").then(reslut => {
                   item.bind.data.forEach(d => {
                     d.hidden = true
                   })
                   item.bind.data.forEach(d => {
                     reslut.rows.forEach(j => {
                       if (d.key == j.WHSE_no) {
                         d.hidden = false
                       }
                     })
                   })
                 })
     
               }
             })
        */
        //--end
        let rows = document.querySelectorAll(".grid-detail .el-table__body .el-table__row")
        setTimeout(() => {
          let testInputDom = rows[index].querySelectorAll("td")[5].querySelector("input")
          this.rowschild = rows[0].childNodes[2]
          testInputDom.addEventListener("keyup", (e) => {
            //在这里去请求判断库存数量
            if (+e.target.value) {
              if (row.AvailableQuantity < +e.target.value) {
                this.base.ElMessageFn("领用数量大于可用数量")
              } else {
                ElMessage.closeAll()
              }
              /*
                    if (row.WHSE_name) {
                      let url = `api/q_goods_inventory/getgoodsquantity?kw=${row.WHSE_name}&bm=${row.Goods_sub}`
                      this.http.post(url, {}, "").then(({ rows }) => {
                        try {
      
                          if (typeof rows[0] == "object") {
                            let data = rows[0]
                            let off = +data.goods_inventory_quantity < + e.target.value || e.target.value == undefined
                            if (off) {
                              this.$message.error("此商品在该库位实际库存" + data.goods_inventory_quantity)
                              e.target.blur()
                              setTimeout(() => {
                                row.Goods_num = null
                                setTimeout(() => {
                                  e.target.focus()
                                }, 0)
                              }, 0)
                            }
                          } else if (rows[0] == null) {
                            this.$message.error("此商品在该库位暂无库存")
                            e.target.blur()
                            setTimeout(() => {
                              row.Goods_num = null
                              setTimeout(() => {
                                e.target.focus()
                              }, 0)
                            }, 0)
                          }
                        } catch (error) {
                          console.log("错误", error);
                        }
                      })
                    }
              */
            } else {
              this.base.ElMessageFn("请输入有效数字")
            }
          })
        }, 0)
        return true
      }
      // ,
      // this.detailOptions.columns.forEach(x => {
      //   if (x.field == 'WHSE_name') {
      //     x.onChange = (column, row, tableData) => {
      //       if (column.Goods_num) {
      //         this.getInventoryNum(column, column.Goods_num)
      //       }
      //     }
      //   }
      // })

    },
    async searchBefore(param) {
      //界面查询前,可以给param.wheres添加查询参数
      //返回false，则不会执行查询
      if (this.$route.path != "/q_produce_use") {
        param.wheres = param.wheres.filter(item => item.name != "Produce_use")
        this.$route.query = {}
      }
      if (this.$route.path == "/q_produce_use" && JSON.stringify(this.$route.query) != '{}') {
        await this.base.setSearchBefore(this, "Produce_use", param)
        // const sectionState = ["[null,null]",JSON.stringify(["",null]),JSON.stringify([null,""]),JSON.stringify(["",""])]
        // const dateState=sectionState.includes(JSON.stringify(this.searchFormFields.CreateDate))
        // if (this.searchFormFields.Voucher_sub||this.searchFormFields.Goods_sub||this.searchFormFields.Goods_name||this.searchFormFields.Proposer ||!dateState) {
        //    param.wheres=param.wheres.filter(item=>item.name!="Produce_use")
        //   this.$route.query = {}
        // }
      }
      return true;
    },
    searchAfter(result) {
      //查询后，result返回的查询数据,可以在显示到表格前处理表格的值
      return true;
    },
    delBefore(ids, rows) { //查询界面的表删除前 ids为删除的id数组,rows删除的行
      let auditStatus = rows.some(x => {
        return x.AuditStatus == 1
      });
      if (auditStatus) {
        this.base.ElMessageFn('不支持删除审核通过数据')
        return false;
      }
      return true;
    },
    delDetailRow(rows) { //弹出框删除明细表的行数据(只是对table操作，并没有操作后台)
      console.log(rows)
      return true;
    },
    async addBeforeAsync(formData) {
      this.storeRemoveForm()
      return this.testAdd(formData)
      //  return true
    },
    async updateBeforeAsync(formData) {
      //编辑保存前formData为对象，包括明细表、删除行的Id
      this.storeRemoveForm()
      return this.testAdd(formData)
      // return true
    },
    rowClick({
      row,
      column,
      event
    }) {
      //查询界面点击行事件
      this.$refs.table.$refs.table.toggleRowSelection(row);
    },
    detailRowClick({
      row,
      column,
      event
    }) {
      this.$refs.detail.$refs.table.toggleRowSelection(row);
      if (this.$route.path != "/q_produce_use" || this.rowAuditStatus != 0) { //|| !this.CreateUserBoole
        return
      }
      if (column.property == "Goods_num" || column.property == "Remark") {
        let dom = event.target
        if (dom.nodeName != "SPAN") {
          setTimeout(() => {
            let inpDom = dom.querySelector("input")
            inpDom.focus()
          }, 0)
        }
      }
    },
    onModelClose(iconClick) {
      //iconClick=true为点击左中上角X触发的关闭事件
      //如果返回 false不会关闭弹出框 
      //return false;
      this.storeRemoveForm()
      this.$store.commit("setTabelText", true)
      this.boxModel = false;
    },
    async modelOpenBefore(row) {
      this.$store.commit("setTabelText", false)
      this.CreateUserBoole = row.CreateID == this.$store.state.userID
      this.rowAuditStatus = await row.AuditStatus
      if (JSON.stringify(row) == "{}") {
        this.rowAuditStatus = 0
        this.CreateUserBoole = true
      }
      if (this.$route.path != "/q_produce_use" || this.rowAuditStatus != 0) { //|| !this.CreateUserBoole
        this.boxButtons[0].hidden = true
        this.detailOptions.buttons.forEach(item => {
          if (item.name != "导出" && item.name != "刷新") {
            item.hidden = true
          }
        })
      } else {
        this.boxButtons[0].hidden = false
        this.detailOptions.buttons.forEach(item => item.hidden = false)
      }
    },
    modelOpenAfter(row) {
      this.rowschild = null
      this.editFormFields.Production_state = 1
      this.editFormOptions.forEach(item => {
        item.forEach(x => {
          if (x.field == "WHSE_jg") {
            x.onChange = async (e) => {
              console.log("机构变化", e)
              this.editFormFields.WHSE_no = null
              if(!e)return;
              let url = `api/q_produce_use/scgw?jg=${e}`
              await this.http.post(url, {}, "").then((res) => {
                try {
                  console.log("生产库位", res);
                  if (+res >= 0) {
                    this.editFormFields.WHSE_no = res
                  }else{
                    this.base.ElMessageFn(res)
                  }
                } catch (error) {
                  console.log("错误", error);
                }

              })
              //后台去更改所有子表中生产工位
              // let detailDate = this.$refs.detail.rowData
              // detailDate.forEach(o => {
              //   o.WHSE_no=null
              // })
            }
          }
          if (x.field == "Production_state") {
            try {
              x.hidden = true
            } catch (error) {
              console.error(error);
            }
          }
          if (x.field == "Voucher_sub" || x.field == "Goods_sub" || x.field == "Goods_name" || x.field == "WHSE_no") {
            x.disabled = true

          } else {
            x.disabled = false
          }
          if(this.currentAction!="Add"&&x.field == "WHSE_jg"){
            x.disabled = true
          }
          if (this.$route.path != "/q_produce_use" || this.rowAuditStatus != 0) { //|| !this.CreateUserBoole
            x.disabled = true
            if (x.field == "Goods_name" || x.field == "Goods_num") {
              x.extra = null
            }
          } else {
            if (x.field == "Goods_name") {
              x.extra = {
                icon: "el-icon-zoom-in",
                text: "选择产品",
                style: "color:#3a8ee6;font-size:13px;cursor:default",
                click: () => {
                  this.$store.commit("setTabelText", true)
                  this.$refs.modelHeader.open()
                  // this.$refs.detail.rowData.forEach(item => {
                  //   item.Goods_num = item.Goods_num_copy
                  // })
                }
              }
            }
            if (item.field == "Goods_num") {
              item.extra = {
                icon: "el-icon-close",
                // text: "X",
                style: "color:#3a8ee6;font-size:13px;cursor:default;background-color: #f5f7fa;padding: 10px 15px;border-radius: 5px;box-shadow: 2px 2px 2px #d4d6d9;",
                click: () => {
                  console.log("this.editFormFields.Goods_num>0", this.editFormFields.Goods_num > 0)
                  if (this.editFormFields.Goods_num > 0) {

                    this.$refs.detail.rowData.forEach(item => {
                      if (item.Goods_num) {
                        item.Goods_num = item.Goods_num * this.editFormFields.Goods_num
                      }
                    })
                  } else {
                    this.$refs.detail.rowData.forEach(item => {
                      item.Goods_num = 0
                    })
                  }

                }
              }
            }
          }
        })
      })
    },
    async getInventoryNum(rowObj, val) {
      let url = `api/q_goods_inventory/getgoodsquantity?kw=${rowObj.WHSE_name}&bm=${rowObj.Goods_sub}`
      await this.http.post(url, {}, "").then(({
        rows
      }) => {
        try {
          if (typeof rows[0] == "object") {
            let data = rows[0]
            let off = +data.goods_inventory_quantity < +val || val == undefined
            if (off) {
              this.$message.error("此商品在该库位实际库存" + data.goods_inventory_quantity)
              setTimeout(() => {
                rowObj.Goods_num = null
              }, 0)
            }
          } else if (rows[0] == null) {
            this.$message.error("此商品在该库位暂无库存")
            rowObj.Goods_num = null
          }
        } catch (error) {
          console.log("错误", error);
        }

      })
    },
    // async getSummary(formData) {
    //   let detailRowData = this.$refs.detail.rowData
    //   let num = 0
    //   await detailRowData.forEach(item => {
    //     if (item.Goods_sub && item.Goods_name && item.Goods_num && item.WHSE_name) num++
    //   })
    //   if (detailRowData.length == num) {
    //     return true
    //   } else {
    //     this.$message.error("请正确选择商品")
    //     return false
    //   }
    // },
    testAdd(formData) {
      if (!this.$refs.detail.rowData.length) {
        this.base.ElMessageFn('明细表不可为空', "error")
        return false
      }
      let boole2 = formData.detailData.some(item => +item.Goods_num === 0)
      if (boole2) {
        this.base.ElMessageFn("明细表中领用数量不可为零")
        return false;
      }
      let boole = formData.detailData.some(item => item.Goods_num == "" || item.Goods_num == null || item.Goods_num == undefined)
      if (boole) {
        this.base.ElMessageFn("明细表中请填写领用数量")
        return false;
      }
      let boole3 = formData.detailData.every(item => +item.Goods_num > 0 && +item.Goods_num)
      if (!boole3) {
        this.base.ElMessageFn("明细表中领用数量请填写有效正数")
        return false;
      }
      return true
    },
  }
};
export default extension;